// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
import compression from 'vite-plugin-compression'
import components from 'unplugin-vue-components/vite'
import autoImport from 'unplugin-auto-import/vite'
import { VarletImportResolver } from '@varlet/import-resolver'
import pxtovw from 'postcss-px-to-viewport-8-plugin'

// 仅为 @varlet 组件做移动端适配
// const var_pxtovw = pxtovw({
//   viewportWidth: 375,
//   unitPrecision: 6,
//   unitToConvert: 'px',
//   viewportUnit: 'vmin',
//   fontViewportUnit: 'vmin',
//   propList: ['*'],
// })

export default defineConfig(({ command, mode }): any => {
  let env = loadEnv(mode, process.cwd())
  return {
    publicPath: './',
    base: './',
    plugins: [
      vue(),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]',
      }),
      compression({
        algorithm: 'gzip', // 指定压缩算法为gzip,[ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
        ext: '.gz', // 指定压缩后的文件扩展名为.gz
        threshold: 10240, // 仅对文件大小大于threshold的文件进行压缩，默认为10KB
        deleteOriginFile: false, // 是否删除原始文件，默认为false
        filter: /\.(js|css|json|html|ico|svg)(\?.*)?$/i, // 匹配要压缩的文件的正则表达式，默认为匹配.js、.css、.json、.html、.ico和.svg文件
        compressionOptions: { level: 9 }, // 指定gzip压缩级别，默认为9（最高级别）
        verbose: true, //是否在控制台输出压缩结果
        disable: true, //是否禁用插件
      }),
      components({
        resolvers: [VarletImportResolver()],
      }),
      autoImport({
        resolvers: [VarletImportResolver({ autoImport: true })],
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve('./src'), // 相对路径别名配置，使用 @ 代替 src
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData:
            '@import "@/styles/mixin.scss";@import "./src/styles/variable.scss";',
        },
      },
      postcss: {
        plugins: [
          //var_pxtovw
          pxtovw({
            viewportWidth: 375,
            unitPrecision: 6,
            unitToConvert: 'px',
            viewportUnit: 'vmin',
            fontViewportUnit: 'vmin',
            propList: ['*'],
          }),
        ],
      },
    },
    server: {
      host: true,
      open: false,
      https: false,
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_SERVE,
          changeOrigin: true,
          // rewrite: (path) => {
          //   let baseUrl = env.VITE_APP_BASE_API
          //   let regex = new RegExp(`^${baseUrl}/`)
          //   return path.replace(regex, '')
          // },
        },
        '/news': {
          target: 'https://www.mxnzp.com/api/',
          changeOrigin: true,
        },
        '/mohuImg': {
          target: 'https://img.moehu.org',
          changeOrigin: true,
          rewrite: (path: any) => path.replace(/^\/mohuImg/, ''),
        },
      },
    },
    build: {
      sourcemap: command === 'build' ? false : 'inline',
      outDir: 'dist', //指定输出目录
      assetsDir: 'assets', //指定静态资源存储目录(相对于outDir)
      // 将js、css文件分离到单独文件夹
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
        },
      },
      chunkSizeWarningLimit: 1500,
    },
  }
})
